from flask import Flask, request, jsonify
from school import School

app = Flask(__name__)


@app.route('/api/all-info', methods=['POST'])
def get_all_info():
    """
    综合接口：使用账号密码登录后返回用户信息、成绩信息和课表信息
    请求参数：account(账号), psw(密码), semester(学期，可选，默认2024-2025-2)
    """
    data = request.json
    account = data.get('account')
    psw = data.get('psw')
    semester = data.get('semester', '2024-2025-2')  # 默认学期
    
    if not account or not psw:
        return jsonify({
            "code": 400,
            "data": None,
            "msg": "账号或密码不能为空"
        }), 400
    
    try:
        # 创建School实例并登录
        school = School()
        login_success = school.login_in(account, psw)
        
        if not login_success:
            return jsonify({
                "code": 401,
                "data": None,
                "msg": "登录失败：账号或密码错误"
            }), 401
        
        # 获取用户信息
        user_info = school.get_user_info()
        
        # 获取所有学期成绩
        scores = school.get_all_score()
        
        # 获取专业排名
        ranking_info = school.get_user_major_ranking()
        
        # 获取课表信息
        html = school.get_class_schedule(semester)
        if html:
            schedule = school.parse_class_schedule(html)
            if schedule:
                db_schedule = school.process_schedule_for_db(schedule)
                schedule_data = db_schedule
            else:
                schedule_data = []
        else:
            schedule_data = []
        
        # 返回综合信息
        return jsonify({
            "code": 0,
            "data": {
                "user_info": user_info,
                "scores": scores,
                "schedule": schedule_data,
                "ranking_info": ranking_info
            },
            "msg": "成功"
        }), 200
        
    except Exception as e:
        return jsonify({
            "code": 500,
            "data": None,
            "msg": f"请求处理失败：{str(e)}"
        }), 500

@app.route('/api/schedule', methods=['POST'])
def get_schedule():
    """
    单独获取课表信息接口
    请求参数：account(账号), psw(密码), semester(学期)
    """
    data = request.json
    account = data.get('account')
    psw = data.get('psw')
    semester = data.get('semester')
    
    if not account or not psw:
        return jsonify({
            "code": 400,
            "data": None,
            "msg": "账号或密码不能为空"
        }), 400
    
    if not semester:
        return jsonify({
            "code": 400,
            "data": None,
            "msg": "学期参数不能为空"
        }), 400
    
    try:
        # 创建School实例并登录
        school = School()
        login_success = school.login_in(account, psw)
        
        if not login_success:
            return jsonify({
                "code": 401,
                "data": None,
                "msg": "登录失败：账号或密码错误"
            }), 401
        
        # 获取课表信息
        html = school.get_class_schedule(semester)
        if html:
            schedule = school.parse_class_schedule(html)
            if schedule:
                db_schedule = school.process_schedule_for_db(schedule)
                return jsonify({
                        "code": 0,
                        "data": {
                            "semester": semester,
                            "schedule": db_schedule
                        },
                        "msg": "成功"
                    }), 200
        
        return jsonify({
            "code": 0,
            "data": {
                "semester": semester,
                "schedule": []
            },
            "msg": "成功"
        }), 200
        
    except Exception as e:
        return jsonify({
            "code": 500,
            "data": None,
            "msg": f"请求处理失败：{str(e)}"
        }), 500

@app.route('/api/scores', methods=['POST'])
def get_scores():
    """
    单独获取成绩信息接口
    请求参数：account(账号), psw(密码)
    """
    data = request.json
    account = data.get('account')
    psw = data.get('psw')
    
    if not account or not psw:
        return jsonify({
            "code": 400,
            "data": None,
            "msg": "账号或密码不能为空"
        }), 400
    
    try:
        # 创建School实例并登录
        school = School()
        login_success = school.login_in(account, psw)
        
        if not login_success:
            return jsonify({
                "code": 401,
                "data": None,
                "msg": "登录失败：账号或密码错误"
            }), 401
        
        # 获取所有学期成绩
        scores = school.get_all_score()
        
        return jsonify({
            "code": 0,
            "data": {
                "scores": scores
            },
            "msg": "成功"
        }), 200
        
    except Exception as e:
        return jsonify({
            "code": 500,
            "data": None,
            "msg": f"请求处理失败：{str(e)}"
        }), 500

@app.route('/api/ranking', methods=['POST'])
def get_ranking():
    """
    单独获取排名信息接口
    请求参数：account(账号), psw(密码)
    """
    data = request.json
    account = data.get('account')
    psw = data.get('psw')
    
    if not account or not psw:
        return jsonify({
            "code": 400,
            "data": None,
            "msg": "账号或密码不能为空"
        }), 400
    
    try:
        # 创建School实例并登录
        school = School()
        login_success = school.login_in(account, psw)
        
        if not login_success:
            return jsonify({
                "code": 401,
                "data": None,
                "msg": "登录失败：账号或密码错误"
            }), 401
        
        # 获取专业排名信息
        ranking_info = school.get_user_major_ranking()
        
        return jsonify({
            "code": 0,
            "data": {
                "ranking_info": ranking_info
            },
            "msg": "成功"
        }), 200
        
    except Exception as e:
        return jsonify({
            "code": 500,
            "data": None,
            "msg": f"请求处理失败：{str(e)}"
        }), 500

if __name__ == '__main__':
    # 获取环境变量，默认为调试模式
    import os
    debug_mode = os.environ.get('FLASK_DEBUG', 'True').lower() == 'true'
    
    # 生产环境下应该设置为False
    app.run(debug=debug_mode, host='0.0.0.0', port=5001)